#include "StorageUtility.h"
#include <QStorageInfo>
#include <QFile>
#include <QProcess>

#define PHOTO_SIZE  (100000)
#define VIDEO_SIZE  (360000000)

StorageUtility *StorageUtility::getInstance()
{
    static StorageUtility singleton{};
    return &singleton;
}

int StorageUtility::internalFreePhotoSize()
{
    qreal count = 0;

    syncInternalStorageInfo(&g_internalStorage);
    count = g_internalStorage.freeBytes*1.0f / g_internalStorage.totalBytes;

    return (1.0f-count)*100+0.5;
}

int StorageUtility::internalFreeVideoSize()
{
    int count = 0;

    syncInternalStorageInfo(&g_internalStorage);
    count = g_internalStorage.freeBytes / VIDEO_SIZE;

    return count/2;
}

int StorageUtility::externalFreePhotoSize() {
    qreal count = 0;

    syncInternalStorageInfo(&m_externalStorage, false);
    count = m_externalStorage.freeBytes*1.0f / m_externalStorage.totalBytes;

    return (1.0f-count)*100+0.5;
}

int StorageUtility::externalFreeVideoSize() {
    int count = 0;

    syncInternalStorageInfo(&m_externalStorage, false);
    count = m_externalStorage.freeBytes / VIDEO_SIZE;

    return count/2;
}

bool StorageUtility::isHaveEnoughFreeSize() {
    syncInternalStorageInfo(&g_internalStorage);
    qDebug() << (g_internalStorage.freeBytes>>10>>10);
    if((g_internalStorage.freeBytes>>10>>10) <= 1024) {
        return false;
    } else return true;
}

bool StorageUtility::isHaveDisk() {
    return m_disk.count()>0;
}



int StorageUtility::syncInternalStorageInfo(Storage *info, bool isInternel) {
    QString str;
    if(isInternel) {
        str = "/home/root";
    } else if(m_disk.count()){
        str = "/run/media/"+m_disk[0];
    }

    QStorageInfo internalStorage(str);
    internalStorage.refresh();
    qint64 freeBytes = internalStorage.bytesAvailable();
    qint64 totalBytes = internalStorage.bytesTotal();
    info->freeBytes = freeBytes;
    info->totalBytes = totalBytes;
    return 0;
}

StorageUtility::StorageUtility():QObject(nullptr){
    fwatcher.addPath("/run/media");
    connect(&fwatcher,&QFileSystemWatcher::directoryChanged,this, &StorageUtility::updateDisk);
    updateDisk("/run/media");
}


StorageUtility::~StorageUtility() {

}

void StorageUtility::updateDisk(const QString &path) {
    QDir dir(path);
    QStringList filters;
    filters << "ntfs_*" <<"sd*";
    dir.setNameFilters(filters);
    QStringList list =  dir.entryList();

    for(auto const &item:m_disk) {//移除删除的disk
        if(list.indexOf(item)==-1) {
            m_disk.removeOne(item);
        }
    }

    for(auto const &item:list){//添加新的disk
        if(m_disk.indexOf(item)==-1) {
            m_disk.append(item);
            if(item.indexOf("ntfs_")!=-1) {//挂载ntfs
                QString dev = item;
                QProcess::startDetached(QString("ntfs-3g /dev/%1 /run/media/%2")
                                        .arg(dev.remove(0,5))
                                        .arg(item));
            }
        }
    }
    qDebug()<<m_disk;
}
